package com.jsb.laundry.thirdpartyinterfaces.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jsb.laundry.common.utils.JSBUtil;
import com.jsb.laundry.common.utils.http.HttpUtil;
import com.jsb.laundry.config.properties.WechatMiniPayProperties;
import com.jsb.laundry.jobs.WechatAccessToken;
import com.jsb.laundry.thirdpartyinterfaces.WxThirdPartyInterfacesService;
import com.jsb.laundry.thirdpartyinterfaces.dto.LoginVo;
import com.jsb.laundry.utils.RedisUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;


/**
 * 微信第三方接口实现类
 */
@Service
public class WxThirdPartyInterfacesServiceImpl implements WxThirdPartyInterfacesService {

    @Resource
    private RedisUtil redisUtil;
    @Resource
    private WechatMiniPayProperties wechatMiniPayProperties;

    /**
     * 微信小程序登录 第三方接口 https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/user-login/code2Session.html
     *
     * @param js_code 获取openid标识
     */
    @Override
    public LoginVo login(String js_code) {
        String url = String.format("https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code", wechatMiniPayProperties.getAppId(), wechatMiniPayProperties.getAppSecret(), js_code);
        String sendGet = HttpUtil.sendGet(url, null, null, null);
        JSONObject jsonObject = JSON.parseObject(sendGet);
        String openid = jsonObject.getString("openid");
        String uniOnId = jsonObject.getString("unionid");
        LoginVo loginVo = new LoginVo();
        loginVo.setOpenid(openid);
        loginVo.setUnionid(uniOnId);
        return loginVo;
    }

    /**
     * 获取手机号 第三方接口地址 https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/user-info/phone-number/getPhoneNumber.html
     *
     * @param code 获取手机号标识
     */
    @Override
    public String getPhone(String code) {
//        String accessToken = redisUtil.getCacheObject("wx66259c2db83de8c2");
//        if (JSBUtil.isEmptyString(accessToken)){
        String accessToken = WechatAccessToken.getWxAccessToken("wx66259c2db83de8c2","a751a2d916092083cbd85d4f58ffc0b5");
//        }
        JSONObject jsonCode = new JSONObject();
        jsonCode.put("code", code);
        String sendPost = HttpUtil.sendPost("https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + accessToken, null, JSONObject.toJSONString(jsonCode));
        JSONObject jsonObject = JSON.parseObject(sendPost);
        String phone_info = jsonObject.getString("phone_info");
        JSONObject iphone = JSON.parseObject(phone_info);
        return iphone.getString("purePhoneNumber");
    }
}
